<?php
declare(strict_types=1);
namespace Service\DeclareService;
use Hyperf\Logger\LoggerFactory;
use Service\BaseService;
use Service\Code\Normal;
use Service\PushService\PushYunCangApiService;
use Hyperf\Di\Annotation\Inject;
use App\Amqp\Producer\PayDeclareMessageProducer;
use Hyperf\Amqp\Producer;
use App\Model\BbcModel\Order;
use App\Model\BbcModel\OrderReportStatus;
use App\Model\BbcModel\OrderReportLog;
use Hyperf\Utils\ApplicationContext;
use App\Model\BbcModel\PushAgain;

/**
 * 支付单申报服务
 * @author chenshubo
 */
class PayDeclareService extends BaseService
{
    
    /**
     * @Inject
     * @var Producer
     */
    protected $producer;
    /**
     * 支付单申报
     * @param array $body
     */
    public function payDeclare( array $body )
    {

        sleep(3);
        $pay_sn=$body['pay_sn'];
        $reportOrder=Order::instance()->lists([
            'pay_sn'            => $pay_sn,
          //  'status'            => 20,
            'need_pay_report'   => 1,
            '_fields_'          => 'id,price_order,sn,receive_info,need_order_report,price_express,cid,tax_fee,points_money,pay_sn,pay_time,type,points_money'
        ]);
        $body['reportOrder']=$reportOrder;
        $declare_way= ucfirst($body['pay_type']);
        $className  = "Service\DeclareService\PayDeclareCompany\\{$declare_way}";
        $callMethod = 'reportPay';
        if (!class_exists($className)) {
            return Normal::returnCode(Normal::PAY_GATEWAY_EXCEPTION, "服务类【{$className}】不存在");
        }
        if (!method_exists($className, $callMethod)) {
            return Normal::returnCode(Normal::PAY_GATEWAY_EXCEPTION, "服务类【{$className}】方法【{$callMethod}】不存在");
        }
        \Hyperf\Utils\ApplicationContext::getContainer()
            ->get(LoggerFactory::class)
            ->get('$body','info')
            ->info(json_encode($body));
        try{
            $declare_result = $className::instance()->{$callMethod}($body);
            //return $declare_result;
        } catch ( \Throwable $th ) {
            return Normal::returnCode(Normal::FAIL, "支付申报服务中心异常[{$th->getMessage()},{$th->getFile()},{$th->getLine()}]");
        }
        \Hyperf\Utils\ApplicationContext::getContainer()
            ->get(LoggerFactory::class)
            ->get('$declare_result','info')
            ->info(json_encode($declare_result));
        if($declare_result['code']==Normal::SUC){
            $orderIds= array_column($reportOrder, 'id');
            $orderMaps= array_column($reportOrder, null,'id');
            $pushAgainData=PushAgain::instance()->whereIn('order_id', $orderIds)->get()->toArray();
            $orderReportsData= OrderReportStatus::instance()->whereIn('order_id', $orderIds)->get()->toArray();
            $orderReportsMapsData=array_column($orderReportsData, null,'order_id');
            foreach ($pushAgainData as $key => $value) {
                if($orderMaps[$value['order_id']]['type']==4&&
                        isset($orderReportsMapsData[$value['order_id']])&&
                        $orderReportsMapsData[$value['order_id']]['express_status']!=1
                ){
                    continue;
                }
                if(
                        isset($orderReportsMapsData[$value['order_id']])&&
                        $orderReportsMapsData[$value['order_id']]['pay_report_status']!=1
                ){
                    continue;
                }
                $pushOrder=PushYunCangApiService::instance()->pushYunCangOrderByPushAgain($body['cid'], $value);
                if($pushOrder['code']==Normal::SUC){
                    PushYunCangApiService::instance()->pushYunCangPayByPushAgain($body['cid'], $value);
                }
            }
        }
        return $declare_result;
        //echo json_encode($body,JSON_UNESCAPED_UNICODE);//在这里接收支付结果回调之后进行支付单申报
       
        /* $body = [
            'cid'           => $cid,
            'mn_sid'        => $mn_sid,
            'mnid'          => $mnid,
            'pay_way'       => $payway,
            'order_sn'      => $order_sn,
            'pay_notify'    => $body
        ]; */
        
        //代发商品和门店保税自提商品 ,如果是门店保税自提的  还需要增加物流单申报信息
        //支付单申报完成之后，推送云仓订单
        //支付单申报失败，不进行推送云仓订单流，并且记录更新订单数据，店铺后台或者渠道后台可以重新发起支付单申报流程
//        PushYunCangApiService::instance()->push($cid, $method);
//        return Normal::returnCode(Normal::SUC,"申报成功");
    }
    
    /**
     * 发布消息队列
     * @param array $msg
     */
    public function publishMsg( array $msg  = [] )
    {
        try {
            $handlerMessage = new PayDeclareMessageProducer($msg);
            $producer = ApplicationContext::getContainer()->get(Producer::class);
            $result = $producer->produce($handlerMessage,true);
            if( $result ) {
                return Normal::returnCode(Normal::SUC,"发布成功");
            }
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[100000]");
        } catch ( \Throwable $e ) {
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[{$e->getMessage()},{$e->getLine()},{$e->getFile()}]");
        }
    }
    
    /**
     * 支付单申报成功/失败后数据处理
     * @param string $sn
     * @param int $order_id
     * @param string $content
     * @param bool $success
     * @param array $subOrderExtends
     * @return type
     */
    public function dealDeclareResult(string $sn,int $order_id,string $content,bool $success=true,array $subOrderExtends=[]) {
        if(empty($subOrderExtends)){
            $orderReportStatusFlag=OrderReportStatus::instance()->info(['sn'=>$sn]);
        }else{
            $orderReportStatusFlag=isset($subOrderExtends['OrderReportStatusMapList'][$sn])?true:false;
        }
        if($success){
            if($orderReportStatusFlag){
                OrderReportStatus::instance()->edit(['sn'=>$sn],['pay_report_status'=>1,'pay_report_time'=>time()]);
                
            }
            OrderReportLog::instance()->add(['order_id'=>$order_id,'sn'=>$sn,'content'=>$content,'cd'=>time()]);
            if(!empty($subOrderExtends)){
                Order::instance()->edit(['sn'=>$sn],['pay_serial_extend'=>$subOrderExtends['pay_serial_extend']]);
            }
        }else{
            if($orderReportStatusFlag){
                OrderReportStatus::instance()->edit(['sn'=>$sn],['pay_report_status'=>2,'pay_report_time'=>time()]);
            }
            OrderReportLog::instance()->add(['order_id'=>$order_id,'sn'=>$sn,'content'=>$content,'cd'=>time()]);
            Order::instance()->edit(['sn'=>$sn],['report_success'=>0]);
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
}
